package com.lej.share.core

import android.app.Activity
import android.app.Application
import android.content.ClipboardManager
import android.content.Context
import android.os.Build
import android.os.Bundle
import com.qmuiteam.qmui.util.QMUIActivityLifecycleCallbacks
import com.tencent.mm.opensdk.utils.Log
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine

abstract class CheckShareCodeLifeCycleCallback : Application.ActivityLifecycleCallbacks {
    var lastPauseTime = 0L
    override fun onActivityPaused(activity: Activity) {
        lastPauseTime = System.currentTimeMillis()
    }

    override fun onActivityStarted(activity: Activity) {
    }

    override fun onActivityDestroyed(activity: Activity) {
    }

    override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
    }

    override fun onActivityStopped(activity: Activity) {
    }

    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
    }

    override fun onActivityResumed(activity: Activity) {
        if (System.currentTimeMillis() - lastPauseTime < 2000) return
        GlobalScope.launch {
            kotlin.runCatching {
                val pair = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) getClipboardDataAndroidQ(activity)
                else getClipboardData(activity)
                if (pair?.second.isNullOrEmpty()) return@launch
                val time = pair!!.first
                val text = pair.second!!
                checkTimeAndText(time, text, activity)
            }.onFailure {
                Log.i("剪贴板", it.message)
            }
        }
    }

    abstract fun checkTimeAndText(time: Long, text: String, activity: Activity)

    private fun getClipboardData(app: Activity): Pair<Long, String?>? {
        val manager = app.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        if (manager.hasPrimaryClip() && manager.primaryClip!!.itemCount > 0) {
            val timeStamp = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                manager.primaryClip?.description?.timestamp ?: -1L
            } else -1L
            return timeStamp to manager.primaryClip?.getItemAt(0)?.text?.toString()
        }
        return null
    }

    private suspend fun getClipboardDataAndroidQ(activity: Activity): Pair<Long, String?>? {
        return suspendCoroutine<Pair<Long, String?>?> {
            var runnable: Runnable? = null
            runnable = Runnable {
                val manager = activity.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
                if (manager.hasPrimaryClip() && manager.primaryClip!!.itemCount > 0) {
                    val timeStamp = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        manager.primaryClip?.description?.timestamp ?: -1L
                    } else {
                        -1L
                    }
                    val item = manager.primaryClip!!.getItemAt(0)
                    it.resume(timeStamp to item.text?.toString())
                    return@Runnable
                }
                it.resume(null)
                activity.window.decorView.removeCallbacks(runnable)
            }
            activity.window.decorView.post(runnable)
            activity.application.registerActivityLifecycleCallbacks(object : QMUIActivityLifecycleCallbacks(activity) {
                override fun onTargetActivityDestroyed() {
                    activity.window.decorView.removeCallbacks(runnable)
                }
            })
        }
    }
}
